<template>
    <el-card class="box-card" style="width: 1080px">
      <!-- --------------------  搜索------------------------------- -->
      <!-- <div slot="header" class="clearfix">
        <el-form :inline="true" :model="query">
          <el-form-item>
            <el-input
              v-model="query.realName"
              placeholder="用户名"
              :clearable="true"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="query.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始注册日期"
              end-placeholder="结束注册日期"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadUsers"
              ><i class="el-icon-search"></i
            ></el-button>
            <el-button type="success" @click="dialog.addshow = true"
              >添加</el-button
            >
          </el-form-item>
        </el-form>
      </div> -->

      <!-- ----------------------表格--------------------------- -->
      <el-table :data="userList" border style="width: 100%">
        <el-table-column prop="tel" label="电话" width="180"> </el-table-column>
        <el-table-column prop="realName" label="姓名" width="120">
        </el-table-column>
        <el-table-column prop="birthday" label="生日" width="180">
        </el-table-column>
        <el-table-column label="头像" show-overflow-tooltip width="160">
          <template slot-scope="scope">
            <el-link @click="downLoad(scope.row.headImg)" target="_blank">
            <img
              :src="scope.row.headImg"
              alt=""
              style="width: 60px; height: 60px"
            />
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="deptName" label="部门" width="120">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row.id)"
              >编辑</el-button
            >
            <el-popconfirm
              title="这是一段内容确定删除吗？"
              @confirm="handleDelete(scope.row.id)"
            >
              <el-button slot="reference" size="mini" type="danger"
                >删除</el-button
              >
            </el-popconfirm>
            <el-button type="danger" size="mini" @click="assignRole(scope.row.id)"
              >分配角色</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.currentPage"
        :page-sizes="page.pageSizes"
        :page-size="query.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
      >
      </el-pagination>
      <!-- -----------------------添加dialog------------------------------------------------------ -->
      <!-- <el-dialog title="添加用户" :visible.sync="dialog.addshow" width="30%">
        <el-form :model="addForm" :rules="rules" ref="addForm">
          <el-row>
            <el-col :span="12"
              ><el-form-item
                label="账号"
                :label-width="formLabelWidth"
                prop="tel"
              >
                <el-input v-model="addForm.tel" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="姓名" :label-width="formLabelWidth">
                <el-input
                  v-model="addForm.realName"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="头像" prop="headImg" hidden>
                <el-input v-model="addForm.headImg" clearable></el-input>
              </el-form-item>
              <el-form-item label="密码" :label-width="formLabelWidth">
                <el-input
                  v-model="addForm.password"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="生日" :label-width="formLabelWidth">
                <el-date-picker
                  v-model="addForm.birthday"
                  type="date"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </el-form-item>
  
              <el-form-item label="部门" :label-width="formLabelWidth">
                <el-select v-model="addForm.deptId" placeholder="请选择部门">
                  <el-option
                    v-for="(dept, index) in deptList"
                    :key="index"
                    :label="dept.deptName"
                    :value="dept.id"
                  ></el-option>
                </el-select> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-upload
                class="avatar-uploader"
                action="http://localhost:9000/uploadoss"
                name="file"
                :headers="upload.headerObj"
                :show-file-list="false"
                :on-success="handleSuccess"
                :before-upload="beforeUpload"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialog.addshow = false">取 消</el-button>
          <el-button type="primary" @click="addUser">提 交</el-button>
        </div>
      </el-dialog> -->
  
      <!-- -----------------------修改dialog------------------------------------------------------ -->
      <!-- <el-dialog title="修改用户" :visible.sync="dialog.updateshow" width="30%">
        <el-form :model="form">
          <el-form-item label="账号" :label-width="formLabelWidth">
            <el-input v-model="updateForm.tel" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="姓名" :label-width="formLabelWidth">
            <el-input v-model="updateForm.realName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" :label-width="formLabelWidth">
            <el-input v-model="updateForm.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="生日" :label-width="formLabelWidth">
            <el-date-picker
              v-model="updateForm.birthday"
              type="date"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
  
          <el-form-item label="部门" :label-width="formLabelWidth">
            <el-select v-model="updateForm.deptId" placeholder="请选择部门">
              <el-option
                v-for="(dept, index) in deptList"
                :key="index"
                :label="dept.deptName"
                :value="dept.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialog.updateshow = false">取 消</el-button>
          <el-button type="primary" @click="updateUser">提 交</el-button>
        </div>
      </el-dialog> -->
  
      <!-- -----------------------授角色dialog------------------------------------------------------ -->
      <!-- <el-dialog
        title="用户授权"
        :visible.sync="dialog.assingRolesVisible"
        width="30%"
      >
        <el-checkbox-group v-model="checkList">
          <el-checkbox
            :label="item.id"
            v-for="(item, index) in roleList"
            :key="index"
            >{{ item.roleName }}</el-checkbox
          >
        </el-checkbox-group>
  
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialog.assingRolesVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateRole">提 交</el-button>
        </div>
      </el-dialog>-->
    </el-card> 
  </template>
  
  <script>
  export default {
    data() {
      return {
        //  imageUrl: '',
        //  upload: {
        //   headerObj: {
        //     //Spring security时需要传递token,否则不需要该配置
        //     Authorization: sessionStorage.getItem("authorization"),
        //   },
        // },
        // uid: 0,
        // checkList: [], //选中的角色
        // roleList: [], //所有角色
        // userList: [],
        // deptList: [],
        // page: {
        //   pageSizes: [5, 10, 20, 50, 100], //下拉列表中的数组
        //   total: 0, //一共有多少条数据
        // },
        // query: {
        //   currentPage: 1, //代表当前页
        //   pageSize: 5, //代表每页显示多少条数据
        //   realName: "",
        //   dateRange: [],
        // },
        // dialog: {
        //   addshow: false,
        //   updateshow: false,
        //   assingRolesVisible: false,
        // },
        // addForm: {},
        // updateForm: {},
        // rules: {
        //   tel: [
        //     { required: true, message: "请输入电话号码", trigger: "blur" },
        //     { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        //   ],
        //   region: [
        //     { required: true, message: "请选择活动区域", trigger: "change" },
        //   ],
        //   date1: [
        //     {
        //       type: "date",
        //       required: true,
        //       message: "请选择日期",
        //       trigger: "change",
        //     },
        //   ],
        //   date2: [
        //     {
        //       type: "date",
        //       required: true,
        //       message: "请选择时间",
        //       trigger: "change",
        //     },
        //   ],
        //   type: [
        //     {
        //       type: "array",
        //       required: true,
        //       message: "请至少选择一个活动性质",
        //       trigger: "change",
        //     },
        //   ],
        //   resource: [
        //     { required: true, message: "请选择活动资源", trigger: "change" },
        //   ],
        //   desc: [{ required: true, message: "请填写活动形式", trigger: "blur" }],
        // },
      };
    },
    methods: {
      // 下载文件
      downLoad(picture) {
        let pic = picture.substr(picture.lastIndexOf("/") + 1);
        this.$axios
          .get("/downLoadFile", {
            params: { filename: pic },
            responseType: "blob",
          })
          .then((res) => {
            let url = window.URL.createObjectURL(new Blob([res.data]));
            let link = document.createElement("a");
            link.style.display = "none";
            link.href = url;
            link.setAttribute("download", pic); //指定下载后的文件名，防跳转
            document.body.appendChild(link);
            link.click();
            // 释放内存
            window.URL.revokeObjectURL(link.href);
          })
          .catch(function (error) {
            console.log(error);
          });
      },
      handleSuccess(res, file) {
          //this.imageUrl = URL.createObjectURL(file.raw);
          this.imageUrl = res.message;//显示
          this.addForm.headImg = res.message;//表单提交时传给服务器的
        },
        beforeUpload(file) {
          const isJPG = file.type === 'image/jpeg';
          const isLt2M = file.size / 1024 / 1024 < 2;
  
          if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG 格式!');
          }
          if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
          }
          return isJPG && isLt2M;
        },
      updateRole() {
        this.$axios
          .post("roles", {
            uid: this.uid,
            rids: this.checkList,
          })
          .then((res) => {
            if (res.data.code == 200) {
              this.$message.success("授权成功");
              this.dialog.assingRolesVisible = false;
              this.checkList = [];
              this.uid = 0;
            }
          });
      },
      assignRole(id) {
        this.dialog.assingRolesVisible = true;
        this.$axios.get("/roles/" + id).then((res) => {
          this.uid = id;
          this.roleList = res.data.data.roleList;
          this.checkList = res.data.data.checkList;
        });
      },
      loadUsers() {
        this.$axios.post("/users/query", this.query).then((res) => {
          this.userList = res.data.data.userList;
          this.page.total = res.data.data.total;
        });
      },
      loadDepts() {
        this.$axios.get("/depts").then((res) => {
          this.deptList = res.data.data.deptList;
        });
      },
      addUser() {
        this.$axios.post("/users", this.addForm).then((res) => {
          if (res.data.code == 200) {
            this.dialog.addshow = false; //关掉模态框
            this.loadUsers(); //重新加载数据
            this.$refs.addForm.resetFields();
            //this.addForm = {}
          }
        });
      },
      updateUser() {
        this.$axios.put("/users", this.updateForm).then((res) => {
          if (res.data.code == 200) {
            this.dialog.updateshow = false; //关掉模态框
            this.loadUsers(); //重新加载数据
          }
        });
      },
      handleEdit(id) {
        //显示修改模态框
        this.dialog.updateshow = true;
        //查询对应的数据
        this.$axios.get("/users/" + id).then((res) => {
          this.updateForm = res.data.data.user;
        });
      },
      handleDelete(id) {
        //查询对应的数据
        this.$axios.delete("/users/delete/" + id).then((res) => {
          if (res.data.code == 200) {
            this.$message.success("删除成功");
            this.loadUsers(); //重新加载数据
          } else {
            this.$message.success(res.data.message);
          }
        });
      },
      handleSizeChange(val) {
        //当每页数据改变时
        this.query.pageSize = val;
        this.loadUsers();
      },
      handleCurrentChange(val) {
        //当点击页码时
        this.query.currentPage = val;
        this.loadUsers();
      },
    },
    mounted() {
    this.$store.getters.obtainUserInfo.user;
    //   this.loadUsers();
    //   this.loadDepts();
    },
  };
  </script>
  <style>
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  </style>